package cn.flying.cloud.task.service.impl;

import javax.annotation.Resource;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.PageRequest;
import cn.flying.cloud.base.common.vo.PageResponse;
import cn.flying.cloud.task.core.quartz.enums.JobStatusEnum;
import cn.flying.cloud.task.core.quartz.exception.TaskException;
import cn.flying.cloud.task.core.service.JobService;
import cn.flying.cloud.task.entity.TaskJobInfo;
import cn.flying.cloud.task.mapper.TaskJobInfoMapper;
import cn.flying.cloud.task.service.TaskJobInfoService;

/**
 * 定时任务配置信息 服务实现类
 *
 * @author admin
 * @since 2025-01-24 09:31:45
 */
@Service
public class TaskJobInfoServiceImpl extends ServiceImpl<TaskJobInfoMapper, TaskJobInfo> implements TaskJobInfoService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JobService jobService;

    /**
     * 查询总数
     *
     * @param taskJobInfo
     * @return
     */
    @Override
    public long countObj(TaskJobInfo taskJobInfo) {
        return this.count(getLambdaQueryWrapper(taskJobInfo));
    }

    /**
     * 分页查询定时任务配置信息数据
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<TaskJobInfo> getPageList(PageRequest<TaskJobInfo> request) {
        TaskJobInfo param = request.getParam();
        LambdaQueryWrapper<TaskJobInfo> wrapper = getLambdaQueryWrapper(param);
        // wrapper TODO
        Page<TaskJobInfo> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()), wrapper);
        return new PageResponse<>(page.getTotal(), (int) page.getCurrent(), page.getRecords());
    }

    /**
     * 构建查询对象
     *
     * @param param
     * @return
     */
    private LambdaQueryWrapper<TaskJobInfo> getLambdaQueryWrapper(TaskJobInfo param) {
        LambdaQueryWrapper<TaskJobInfo> wrapper = new LambdaQueryWrapper<>();
        if (param != null) {
            if (Ft.String.isNotBlank(param.getServiceCode())) {
                wrapper.eq(TaskJobInfo::getServiceCode, param.getServiceCode());
            }
            if (Ft.String.isNotBlank(param.getJobName())) {
                wrapper.eq(TaskJobInfo::getJobName, param.getJobName());
            }
            if (Ft.String.isNotBlank(param.getJobGroup())) {
                wrapper.eq(TaskJobInfo::getJobGroup, param.getJobGroup());
            }
            if (Ft.String.isNotBlank(param.getJobStatus())) {
                wrapper.eq(TaskJobInfo::getJobStatus, param.getJobStatus());
            }
            if (Ft.String.isNotBlank(param.getStatus())) {
                wrapper.eq(TaskJobInfo::getStatus, param.getStatus());
            }
        }
        return wrapper;
    }

    /**
     * 列表查询定时任务配置信息数据
     *
     * @param taskJobInfo
     * @return
     */
    @Override
    public List<TaskJobInfo> getList(TaskJobInfo taskJobInfo) {
        LambdaQueryWrapper<TaskJobInfo> wrapper = new LambdaQueryWrapper<>();
        // wrapper TODO
        return this.list(wrapper);
    }

    /**
     * 查询定时任务配置信息详情数据
     *
     * @param taskJobInfo
     * @return
     */
    @Override
    public TaskJobInfo getOneObj(TaskJobInfo taskJobInfo) {
        LambdaQueryWrapper<TaskJobInfo> wrapper = new LambdaQueryWrapper<>();
        // wrapper TODO
        return this.getOne(wrapper);
    }

    /**
     * 根据Id查询定时任务配置信息详情数据
     *
     * @param id
     * @return
     */
    @Override
    public TaskJobInfo getObjById(Serializable id) {
        return this.getById(id);
    }

    /**
     * 新增定时任务配置信息数据
     *
     * @param taskJobInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createObj(TaskJobInfo taskJobInfo) {
        taskJobInfo.setJobStatus(JobStatusEnum.STOP.getCode());
        taskJobInfo.setJobTarget("scheduleJobExecution");
        taskJobInfo.setTenantId(Ft.Local.TenantId());
        return this.save(taskJobInfo);
    }

    /**
     * 更新定时任务配置信息数据
     *
     * @param taskJobInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateObj(TaskJobInfo taskJobInfo) {
        TaskJobInfo info = this.getById(taskJobInfo.getId());
        if (!JobStatusEnum.STOP.getCode().equals(info.getJobStatus())) {
            throw new TaskException("修改任务请先停止下线！");
        }
        taskJobInfo.setTenantId(Ft.Local.TenantId());
        return this.saveOrUpdate(taskJobInfo);
    }

    /**
     * 删除定时任务配置信息数据
     *
     * @param taskJobInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteObj(TaskJobInfo taskJobInfo) {
        TaskJobInfo info = this.getById(taskJobInfo.getId());
        if (!JobStatusEnum.STOP.getCode().equals(info.getJobStatus())) {
            throw new TaskException("删除任务请先停止下线！");
        }
        LambdaQueryWrapper<TaskJobInfo> wrapper = getLambdaQueryWrapper(taskJobInfo);
        return this.remove(wrapper);
    }

    /**
     * 根据Id删除定时任务配置信息数据
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(Serializable id) {
        TaskJobInfo taskJobInfo = this.getById(id);
        if (!JobStatusEnum.STOP.getCode().equals(taskJobInfo.getJobStatus())) {
            throw new TaskException("删除任务请先停止下线！");
        }
        return this.removeById(id);
    }

    /**
     * 启动任务
     *
     * @param jobName
     * @param jobGroup
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean startJob(String jobName, String jobGroup) {
        LambdaQueryWrapper<TaskJobInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskJobInfo::getJobName, jobName).eq(TaskJobInfo::getJobGroup, jobGroup);
        TaskJobInfo taskJobInfo = this.getOne(wrapper);
        if (JobStatusEnum.RUNNING.getCode().equals(taskJobInfo.getJobStatus())) {
            throw new TaskException("任务正在运行，不能重复启动！");
        }

        taskJobInfo.setJobStatus(JobStatusEnum.RUNNING.getCode());
        // 加入调度器中启动调度执行
        jobService.startJob(taskJobInfo);

        this.saveOrUpdate(taskJobInfo);
        return false;
    }

    /**
     * 停止任务
     *
     * @param jobName
     * @param jobGroup
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean stopJob(String jobName, String jobGroup) {
        // 从调度器中卸载并删除
        jobService.stopJob(jobName, jobGroup);
        // 修改状态
        TaskJobInfo jobInfo = this.getOne(new LambdaQueryWrapper<TaskJobInfo>().eq(TaskJobInfo::getJobName, jobName).eq(TaskJobInfo::getJobGroup, jobGroup));
        jobInfo.setJobStatus(JobStatusEnum.STOP.getCode());
        this.saveOrUpdate(jobInfo);
        return true;
    }

    /**
     * 暂停任务
     *
     * @param jobName
     * @param jobGroup
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean pauseJob(String jobName, String jobGroup) {
        // 调度器暂停调度执行
        jobService.pauseJob(jobName, jobGroup);
        // 修改状态
        TaskJobInfo jobInfo = this.getOne(new LambdaQueryWrapper<TaskJobInfo>().eq(TaskJobInfo::getJobName, jobName).eq(TaskJobInfo::getJobGroup, jobGroup));
        jobInfo.setJobStatus(JobStatusEnum.PAUSE.getCode());
        this.saveOrUpdate(jobInfo);
        return false;
    }

    /**
     * 恢复任务
     *
     * @param jobName
     * @param jobGroup
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean resumeJob(String jobName, String jobGroup) {
        // 调度器恢复调度执行
        jobService.resumeJob(jobName, jobGroup);
        // 修改状态
        TaskJobInfo jobInfo = this.getOne(new LambdaQueryWrapper<TaskJobInfo>().eq(TaskJobInfo::getJobName, jobName).eq(TaskJobInfo::getJobGroup, jobGroup));
        jobInfo.setJobStatus(JobStatusEnum.RUNNING.getCode());
        this.saveOrUpdate(jobInfo);
        return true;
    }

    /**
     * 立即触发执行一次任务
     *
     * @param jobName
     * @param jobGroup
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean triggerJob(String jobName, String jobGroup, String param) {
        jobService.triggerJob(jobName, jobGroup, param);
        return true;
    }

    /**
     * 手动补偿处理
     *
     * @param jobName
     * @param jobGroup
     * @param serialNo
     * @param param
     * @param host
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean resolveJob(String jobName, String jobGroup, String serialNo, String param, String host) {
        TaskJobInfo jobInfo = this.getOne(new LambdaQueryWrapper<TaskJobInfo>().eq(TaskJobInfo::getJobName, jobName).eq(TaskJobInfo::getJobGroup, jobGroup));
        jobService.resolveJob(jobInfo, serialNo, param, host);
        return false;
    }
}
